package task

import (
	"fmt"
	"hft/global"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/oschwald/geoip2-golang"
)

// 定期获取ip库

type GetGeoIp struct {
	Spec string
}

func (g *GetGeoIp) downloadFile(url string, destination string) error {
	// 创建 HTTP 客户端
	client := &http.Client{}

	// 发送 GET 请求
	resp, err := client.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// 如果文件已经存在，先删除
	if _, err := os.Stat(destination); err == nil {
		err := os.Remove(destination)
		if err != nil {
			return err
		}
	}

	// 创建文件
	out, err := os.Create(destination)
	if err != nil {
		return err
	}
	defer out.Close()

	// 将响应体拷贝到文件
	_, err = io.Copy(out, resp.Body)
	return err
}

func (g *GetGeoIp) UpdateGeo() {
	err := g.downloadFile(global.OC_CONFIG.IpGeo.Url, global.OC_CONFIG.IpGeo.Source)
	if err != nil {
		fmt.Println("下载文件时发生错误:", err)
	} else {
		fmt.Println("文件下载成功!")
	}
	db, err := geoip2.Open(global.OC_CONFIG.IpGeo.Source)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	global.OC_GEO = db
}

var GeoSpec = &GetGeoIp{
	Spec: "0 0 */7 * *",
}
